//
//  JSTPublishViewController.m
//  KYKJPackDemo
//
//  Created by 01 on 17/5/15.
//  Copyright © 2017年 ???. All rights reserved.
//

#import "JSTPublishViewController.h"
#import "JSTPublishInfoView.h"
#import "ZYQAssetPickerController.h"
#import "JSTPictureViewController.h"

@interface JSTPublishViewController ()<PublishInfoViewDelegate, UINavigationControllerDelegate, ZYQAssetPickerControllerDelegate, UITextViewDelegate, UIImagePickerControllerDelegate>
{
    NSMutableArray *imageArray;
    NSMutableArray *mutableArray;
    ALAssetsLibrary *library;
}
@property (nonatomic,strong) JSTPublishInfoView *publishInfoView;

@property (nonatomic,assign) BOOL isAllstrangecom; //是否允许陌生人评价
@end

@implementation JSTPublishViewController

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    [self.publishInfoView.publishTextView becomeFirstResponder];
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    // 0.创建数组设置基础属性
    [self setUpAttris];

    // 1.创建导航栏上的按钮
    [self setUpNavBarItems];
    
    // 2.创建所有子控件
    [self setUpAllSubViews];
    
    // 3.添加通知
    [KYNotificationCenter addObserver:self selector:@selector(textDidChange) name:UITextViewTextDidChangeNotification object:self.publishInfoView.publishTextView];
}

#pragma mark - setUp初始化
/**
 *  创建数组设置基础属性
 */
- (void)setUpAttris
{
    imageArray = [NSMutableArray array];
    mutableArray = [NSMutableArray array];
    self.automaticallyAdjustsScrollViewInsets = NO;
}

/**
 *  创建导航栏上按钮
 */
- (void)setUpNavBarItems
{
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithTitle:NSLocalizedString(@"取消", nil) titleColor:[UIColor blackColor] target:self action:@selector(cancel)];
    
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithTitle:NSLocalizedString(@"发布", nil) titleColor:[UIColor blackColor] target:self action:@selector(popStatus)];
    
    self.navigationItem.rightBarButtonItem.enabled = NO;
}

/**
 *  创建所有子控件
 */
- (void)setUpAllSubViews
{
    // 1.添加发布动态的view
    [self.view addSubview:self.publishInfoView];
    
    // 2.传递参数
    self.publishInfoView.dynamicId = _dynamicId;
    self.publishInfoView.userNick = _personName;
    
    // 3.创建发布view的内部子控件
    [self.publishInfoView createContent];
}

/**
 *  添加文字输入的通知
 */
- (void)textDidChange
{
    self.navigationItem.rightBarButtonItem.enabled = (self.publishInfoView.publishTextView.text.length != 0);
}

#pragma mark - 取消(提示是否保存记录)
- (void)cancel
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - 发表动态
#pragma mark - 先上传图片在发表
- (void)popStatus
{
    // 0.取得当前要发布的文字
    NSString *statusStr = self.publishInfoView.publishTextView.text;
    if (statusStr.length > 150) {
        [MBProgressHUD showError:NSLocalizedString(@"字数超过限制...", nil)];
    }
    
    // 1.判断dynamicId
    if (_dynamicId) { // 评论或者回复
        NSMutableDictionary *params = [NSMutableDictionary dictionary];
        params[@"content"] = statusStr;
        params[@"id"] = _dynamicId;
        params[@"h_apuid"] = _personId;
        
        [JSTNewServer requestCommitComment:params success:^(NSDictionary *dataDic) {
            KYLog(@"%@", dataDic);
            [self dismissViewControllerAnimated:YES completion:nil];
        } error:^(NSString *errStr) {
            [MBProgressHUD showError:errStr];
        }];
    } else { // 发布状态
        [JSTNewServer requestCommitDynamic:imageArray getContent:self.publishInfoView.publishTextView.text success:^(NSDictionary *dataDic) {
            KYLog(@"%@", dataDic);
            [self dismissViewControllerAnimated:YES completion:nil];
         } error:^(NSString *errStr) {
            [MBProgressHUD showError:errStr];
        }];
    }
}

- (void)publishHealthCircle:(NSString *)imageUrls;
{
    
}

#pragma mark - 访问相机
-(void)visitCamera
{
    //访问相机
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    imagePickerController.delegate = self;
    imagePickerController.sourceType = sourceType;
    imagePickerController.allowsEditing = YES;
    [self presentViewController:imagePickerController animated:YES completion:nil];
}

#pragma mark - 访问相册
-(void)visitPhotograph
{
    ZYQAssetPickerController *picker = [[ZYQAssetPickerController alloc] init];
    picker.maximumNumberOfSelection = 3;
    picker.assetsFilter = [ALAssetsFilter allPhotos];
    picker.showEmptyGroups = NO;
    picker.delegate = self;
    picker.selectionFilter = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
        if ([[(ALAsset*)evaluatedObject valueForProperty:ALAssetPropertyType] isEqual:ALAssetTypeVideo]) {
            NSTimeInterval duration = [[(ALAsset*)evaluatedObject valueForProperty:ALAssetPropertyDuration] doubleValue];
            return duration >= 5;
        } else {
            return YES;
        }
    }];
    
    [self presentViewController:picker animated:YES completion:NULL];
}

#pragma mark - 代理方法
- (void)zoomingPicture:(NSInteger)index
{
    JSTPictureViewController *pvc = [[JSTPictureViewController alloc] init];
    pvc.isHiddenBackBtn = NO;
    [pvc setValueWithImages:imageArray andImagView:index];
    pvc.block = ^(id sender) {
        [imageArray removeAllObjects];
        [imageArray addObjectsFromArray:sender];
        _publishInfoView.imageArr = imageArray;
    };
    [self.navigationController pushViewController:pvc animated:YES];
}

#pragma - 删除选中图片
- (void) deleteSelectPicture:(NSInteger)index
{
    [imageArray removeObjectAtIndex:(index-1)];
}

- (void)getPublishInfoViewWithTag:(NSInteger)tag
{
    
    switch (tag)
    {
            case 0:
            [self visitCamera];
            break;
            case 1:
            [self visitPhotograph];
            break;
            case 2:
            break;
        default:
            break;
    }
}

#pragma mark - 允许陌生人评价
-(void)PublishInfoViewToStrangerWithBut:(UIButton *)but
{
    _isAllstrangecom = but.selected;
    
}
#pragma mark - ZYQAssetPickerControllerDelegate
-(void)assetPickerController:(ZYQAssetPickerController *)picker didFinishPickingAssets:(NSArray *)assets
{
    NSMutableArray *array = [NSMutableArray array];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^ {
        
        dispatch_async(dispatch_get_main_queue(), ^
        {
            
        });
        
        for (int i=0; i < assets.count; i++) {
            ALAsset *asset = assets[i];
            UIImage *tempImg = [UIImage imageWithCGImage:asset.defaultRepresentation.fullScreenImage];
            [array addObject:tempImg];
            
            //回到主线程
            dispatch_async(dispatch_get_main_queue(), ^ {
                if (i == assets.count - 1) {
                    
                    if (imageArray.count + array.count <= 3) {
                        [imageArray addObjectsFromArray:array];
                    } else {
                        
                        [MBProgressHUD showError:NSLocalizedString(@"最多上传三张图片...", nil)];
                        return ;
                    }
                    _publishInfoView.imageArr = imageArray;
                }
            });
        }
    });
}

#pragma mark - textViewDelegate
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    
    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
    }
    
    
//    if (text.length == 0&&[textView.text hasSuffix:@"]"]&&(textView.selectedRange.location == textView.text.length))
//    {
//        NSMutableString *newString=[NSMutableString stringWithString:textView.text];
//
//        //正则表达式
//        NSString *patter=@"\\[[a-zA-Z0-9\\u4e00-\\u9fa5]+\\]";
//        NSError *error=nil;
//        NSRegularExpression *regularExpression=[NSRegularExpression regularExpressionWithPattern:patter options:NSRegularExpressionCaseInsensitive error:&error];
//        //匹配文字
//        NSArray *resultArray=[regularExpression matchesInString:newString options:0 range:NSMakeRange(0, newString.length)];
//        NSTextCheckingResult *match=resultArray.lastObject;
//          [newString deleteCharactersInRange:NSMakeRange(match.range.location, match.range.length - 1)];
//
//        textView.text=newString;
//
//    }else
//    {
//
//    }
    
    return YES;
}

- (void)textViewDidChange:(UITextView *)textView
{
    if (IsStrEmpty(textView.text) && [textView.text hasSuffix:@"]"]) {
        _publishInfoView.placeLabel.hidden = NO;
    } else {
        _publishInfoView.placeLabel.hidden = YES;
    }
    if (textView.text.length > 150) {
        [MBProgressHUD showError:NSLocalizedString(@"字数超出限制...", nil)];
        textView.text = [textView.text substringToIndex:150];
    }
    
    CGSize sizefit = [_publishInfoView.publishTextView sizeThatFits:CGSizeMake(kDeviceWidth-20, MAXFLOAT)];
    [UIView animateWithDuration:0.25 animations:^{
        CGRect frame = _publishInfoView.scrollView.frame;
        frame.origin.y = sizefit.height + kCurrentScreenWidth(20);
        _publishInfoView.scrollView.frame = frame;
    }];
}


#pragma mark - imagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *image = [info valueForKey:UIImagePickerControllerEditedImage];
    if (imageArray.count<3) {
        [imageArray addObject:image];
    } else {
        [MBProgressHUD showError:NSLocalizedString(@"最多上传三张图片...", nil)];
        return;
    }
    _publishInfoView.imageArr = imageArray;
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - PublishInfoServiceDelegate
/*上传图片的回调*/
-(void)getPublishInfoServicePhotoSuccess:(NSArray *)imgUrls
{
    NSMutableString *imageString=[NSMutableString string];
    
    [imgUrls enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        if (idx==0) {
            [imageString appendFormat:@"%@",imgUrls[idx]];
        } else {
            [imageString appendFormat:@"|%@",imgUrls[idx]];
        }
    }];
    //发布健康圈
    [self publishHealthCircle:imageString];
}

/*发布评论的回调*/
-(void)getPublishInfoServiceSendSuccess
{
    [self removeOverFlowActivityView];
    if (_block) {
        _block(nil);
    }
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)getPublishSendEvalFail:(NSString *)error
{
    [self removeOverFlowActivityView];

    [self presentSheet:error];
}

- (void) getPublishInfoPhotoFail:(NSString *)error
{
    [self removeOverFlowActivityView];

    [self presentSheet:error];
}

#pragma mark - 懒加载
- (JSTPublishInfoView *)publishInfoView
{
    if (!_publishInfoView) {
        _publishInfoView = [[JSTPublishInfoView alloc] initWithFrame:CGRectMake(0, 64, kScreenWidth, kScreenHeight - 64) andOwner:self];
        _publishInfoView.delegate = self;
    }
    return _publishInfoView;
}

////保存图片到本地
//-(void)saveImage:(UIImage *)image WithName:(NSString *)imageName
//{
//    NSData *imageData=UIImagePNGRepresentation(image);
//    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
//    NSString *documentDirectory=[paths objectAtIndex:0];
//    NSString *fullPathToFile=[documentDirectory stringByAppendingString:imageName];
//    [imageData writeToFile:fullPathToFile atomically:NO];
//}
@end
